package com.swak.im;

import java.util.Map;

import com.swak.utils.Maps;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

@Getter
@Setter
@Accessors(chain = true)
public class ImConfig {

	private String applicationName;
	private String module;
	private int workerPoolSize;
	private Map<String, Config> configs;

	/**
	 * 合并配置
	 * 
	 * @param other
	 * @return
	 */
	public synchronized ImConfig merge(ImConfig other) {
		this.mergeConfig(other);
		return this;
	}

	private void mergeConfig(ImConfig other) {
		Map<String, Config> otherConfigs = other.getConfigs();
		if (otherConfigs == null || otherConfigs.isEmpty()) {
			return;
		}
		if (this.configs == null || this.configs.isEmpty()) {
			this.configs = otherConfigs;
			return;
		}

		Map<String, Config> myConfigs = Maps.newHashMap(this.configs);
		otherConfigs.forEach((k, v) -> {
			if (myConfigs.containsKey(k)) {
				myConfigs.get(k).mergeConfig(v);
			} else {
				myConfigs.put(k, v);
			}
		});
		this.configs = myConfigs;
	}

	/**
	 * IM 配置：对应 @com.swak.annotation.Im 中的可配置项目 服务配置 > 全局配置 > 本地配置 > 注解配置
	 * 
	 * @author DELL
	 */
	@Getter
	@Setter
	@Accessors(chain = true)
	public static class Config {
		private Integer weight = 1;
		private Boolean opened = Boolean.TRUE;
		private Boolean order;
		private Integer parallel;

		private Config mergeConfig(Config other) {
			if (other.getWeight() != null) {
				this.setWeight(other.getWeight());
			}
			if (other.getOpened() != null) {
				this.setOpened(other.getOpened());
			}
			if (other.getOrder() != null) {
				this.setOrder(other.getOrder());
			}
			if (other.getParallel() != null) {
				this.setParallel(other.getParallel());
			}
			return this;
		}
	}
}
